package com.ruoyi.marketing.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.marketing.domain.AwardPerson;
import com.ruoyi.marketing.domain.UserTask;
import com.ruoyi.marketing.mapper.UserTaskMapper;
import com.ruoyi.marketing.service.IAwardPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.marketing.mapper.MarketingTaskMapper;
import com.ruoyi.marketing.domain.MarketingTask;
import com.ruoyi.marketing.service.IMarketingTaskService;

/**
 * 营销任务Service业务层处理
 *
 * @author hao
 * @date 2023-01-30
 */
@Service
public class MarketingTaskServiceImpl extends ServiceImpl<MarketingTaskMapper, MarketingTask> implements IMarketingTaskService {

    @Autowired
    private UserTaskMapper userTaskMapper;

    @Autowired
    private IAwardPersonService awardPersonService;

    /**
     * 查询营销任务列表
     *
     * @param marketingTask 营销任务
     * @return 营销任务
     */
    @Override
    public List<MarketingTask> selectMarketingTaskList(MarketingTask marketingTask) {
        return getBaseMapper().selectMarketingTaskList(marketingTask);
    }

    /**
     * 获取当前用户所对应的活动任务列表
     *
     * @param activityId 活动编号
     * @return 列表
     */
    @Override
    public List<MarketingTask> getActivityById(Long activityId) {
        LambdaQueryWrapper<MarketingTask> wrapper = Wrappers.<MarketingTask>lambdaQuery()
                .eq(MarketingTask::getActivityId, activityId);
        List<MarketingTask> marketingTasks = getBaseMapper().selectList(wrapper);
        return marketingTasks;
    }

    @Override
    public void getTaskById(Long userId, Long taskId) {
        //标记已完成
        LambdaQueryWrapper<UserTask> wrapper = Wrappers.<UserTask>lambdaQuery()
                .eq(UserTask::getTaskId, taskId);
        UserTask userTask = userTaskMapper.selectOne(wrapper);
        userTask.setState(UserTask.DEFAULT_STATE_YES);//更新状态为已完成
        LambdaUpdateWrapper<UserTask> updateWrapper = new LambdaUpdateWrapper<UserTask>().eq(UserTask::getTaskId, taskId)
                .eq(UserTask::getUserId, userId)
                .set(UserTask::getState, UserTask.DEFAULT_STATE_YES);
        userTaskMapper.update(userTask, updateWrapper);

        // 抽奖数+1设置
        LambdaQueryWrapper<AwardPerson> wrapperPerson = Wrappers.<AwardPerson>lambdaQuery()
                .eq(AwardPerson::getUserId, userId);

        AwardPerson personService = awardPersonService.getOne(wrapperPerson);
        personService.setPrizeNum(personService.getPrizeNum() + 1);//抽奖数+1
        awardPersonService.update(personService,wrapperPerson);

    }
}
